/*
 *  *****************************************************************************
 *  * Copyright (C) 2022 szjzsoft Co.,Ltd
 *  * All Rights Reserved.
 *  * 本软件为深圳市金政软件技术有限公司（平台）研制。未经本公司正式书面同意，其他任何个人、团体
 *  * 不得使用、复制、修改或发布本软件.
 *  ****************************************************************************
 */

package cc.bookcloud.tool.ocr.controller;

import cc.bookcloud.tool.ocr.common.JResult;
import cc.bookcloud.tool.ocr.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.*;


@Slf4j
@Api(tags = "文件加解密操作", value = "文件加解密操作")
@RestController
public class EncryptController {


    /**
     *  文件加密操作
     * @return
     */
    @PostMapping("/fc/encript")
    @ApiOperation(value = "文件加密")
    public JResult enscript(    @ApiParam(name = "filePath",value = "所在目录")  @RequestParam(value = "filePath", required = false)  String filePath,
                                @ApiParam(name = "fileName",value = "待加密文件名称") @RequestParam(value = "fileName", required = false)  String fileName,
                                @ApiParam(name = "finalName",value = "加密后文件名称") @RequestParam(value = "finalName", required = false)  String finalName,
                                @ApiParam(name = "random",value = "随机数") @RequestParam(value = "random", required = false)  int random
                                ) {

        log.info("所在目录："+filePath);
        log.info("待加密文件名称："+fileName);
        log.info("加密后文件名称："+finalName);
        FileUtil.encryptFile(random,filePath,fileName,finalName);
        return JResult.build().ok(1);
    }

    /**
     *  文件解密操作
     * @return
     */
    @PostMapping("/fc/decrypt")
    @ApiOperation(value = "文件解密")
    public JResult descrypt(@ApiParam(name = "filePath",value = "所在目录")  @RequestParam(value = "filePath", required = false)  String filePath,
                            @ApiParam(name = "fileName",value = "待加密文件名称") @RequestParam(value = "fileName", required = false)  String fileName,
                            @ApiParam(name = "finalName",value = "加密后文件名称") @RequestParam(value = "finalName", required = false)  String finalName,
                            @ApiParam(name = "random",value = "随机数") @RequestParam(value = "random", required = false)  int random
    ) {

        log.info("所在目录："+filePath);
        log.info("待加密文件名称："+fileName);
        log.info("加密后文件名称："+finalName);
        FileUtil.decryptFile(random,filePath,fileName,finalName);
        return JResult.build().ok(1);
    }


    private static final int numOfEncAndDec = 0x255;//定义密钥
    private static int dataOfFile = 0;

    /**
     * 加密文件
     *
     * @param srcFile
     * @param encFile
     * @throws Exception
     */
    private static void EncFile(File srcFile, File encFile) throws Exception {
        if (!srcFile.exists()) {
            System.out.println("source file not exixt");
            return;
        }

        if (!encFile.exists()) {
            System.out.println("encrypt file created");
            encFile.createNewFile();
        }
        InputStream fis = new FileInputStream(srcFile);
        OutputStream fos = new FileOutputStream(encFile);

        while ((dataOfFile = fis.read()) > -1) {
            fos.write(dataOfFile ^ numOfEncAndDec);
        }

        fis.close();
        fos.flush();
        fos.close();
    }

    public static void encryptFile(String filePath,String fileName,String finalName){
        InputStream fis = null;
        OutputStream fos = null;
        try {
            File srcFile = new File(filePath + "/" + fileName);
            //int pos = fileName.lastIndexOf(".");
            //String newFileName = fileName.substring(0,pos);
            File outFile = new File(filePath+"/"+finalName+".jar");
            if (!srcFile.exists()) {
                System.out.println("source file not exixt");
                return;
            }

            if (!outFile.exists()) {
                System.out.println("encrypt file created");
                outFile.createNewFile();
            }
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(outFile);

            while ((dataOfFile = fis.read()) > -1) {
                fos.write(dataOfFile ^ numOfEncAndDec);
            }
        }catch (Exception e){
            log.error("加密文件发生了异常！",e);

        }finally {
            try {
                if(fis != null) {
                    fis.close();
                }
                if(fos !=null ) {
                    fos.flush();
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }


    public static void decryptFile(String filePath,String fileName,String finalName){
        InputStream fis = null;
        OutputStream fos = null;
        try {
            File srcFile = new File(filePath + "/" + fileName);
            //int pos = fileName.lastIndexOf(".");
            //String newFileName = fileName.substring(0,pos);
            File outFile = new File(filePath+"/"+finalName);
            if (!srcFile.exists()) {
                System.out.println("source file not exixt");
                return;
            }

            if (!outFile.exists()) {
                System.out.println("encrypt file created");
                outFile.createNewFile();
            }
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(outFile);

            while ((dataOfFile = fis.read()) > -1) {
                fos.write(dataOfFile ^ numOfEncAndDec);
            }
        }catch (Exception e){
            log.error("加密文件发生了异常！",e);

        }finally {
            try {
                if(fis != null) {
                    fis.close();
                }
                if(fos !=null ) {
                    fos.flush();
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }


    /**
     * 解密文件
     *
     * @param encFile
     * @param decFile
     * @throws Exception
     */
    private static void DecFile(File encFile, File decFile) throws Exception {
        if (!encFile.exists()) {
            //加密文件不存在
            return;
        }
        if (!decFile.exists()) {
            //创建解密文件
            decFile.createNewFile();
        }

        InputStream fis = new FileInputStream(encFile);
        OutputStream fos = new FileOutputStream(decFile);

        while ((dataOfFile = fis.read()) > -1) {
            fos.write(dataOfFile ^ numOfEncAndDec);
        }
        fis.close();
        fos.flush();
        fos.close();
    }

}
